package com.tangyuan.user.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.util.DateUtil;
import com.tangyuan.model.User;
import com.tangyuan.model.UserBlackList;
import com.tangyuan.model.UserConcern;
import com.tangyuan.user.mapper.UserBlackListMapper;
import com.tangyuan.user.service.UserBlackListService;
import com.tangyuan.user.service.UserConcernService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserBlackListServiceImpl extends ServiceImpl<UserBlackListMapper, UserBlackList> implements UserBlackListService {

    @Autowired
    UserConcernService userConcernService;


    @Override
    public Result removeBlackList(User user, Long id) {
        Long userId = user.getId();
        //判断是否存在
        if(userId.equals(id)){
            return Result.build(null,667,"不能拉黑自己");
        }
        UserBlackList black = baseMapper.findBlackList(userId, id);
        if (black == null) {
            //没有记录 创建新记录
            UserBlackList userBlackList = new UserBlackList();
            userBlackList.setUserId(userId);
            userBlackList.setBlackUserId(id);
            userBlackList.setCreateTime(DateUtil.changeLocalDateTimeToDate(LocalDateTime.now()));
            baseMapper.insert(userBlackList);
            userConcernService.cancelConcernUser(userId,id);
            userConcernService.cancelConcernUser(id,userId);
            return Result.ok();
        }else if (0 == black.getIsDeleted()) {
            List<UserConcern> concerns = userConcernService.selectUserConcernList(userId, id);
            Integer type = 0;
            if(!CollectionUtils.isEmpty(concerns)){
                UserConcern concern = concerns.get(0);
                type = concern.getType();
            }
            //有记录 存在黑名单 删除黑名单
            baseMapper.updateIsDelete(userId,id,1);
            userConcernService.addConcern(user,id,type);
            return Result.ok();
        }else if (1 == black.getIsDeleted()) {
            //有记录 无黑名单 添加黑名单
            userConcernService.cancelConcernUser(userId,id);
            userConcernService.cancelConcernUser(id,userId);
            baseMapper.updateIsDelete(userId, id,0);
            return Result.ok();
        }
        return Result.ok();
    }
}
